package com.cars.easyEs.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.json.JsonpMapper;
import com.cars.easyEs.common.exception.EsException;
import com.cars.easyEs.common.exception.ResponseCodeEnums;
import com.cars.easyEs.common.response.ResponseInfo;
import com.cars.easyEs.model.DocumentPartESDto;
import com.cars.easyEs.util.ElasticsearchHandle;
import jakarta.annotation.Resource;
import jakarta.json.stream.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.StringReader;

/**
 * @author caoqianfan
 * @date 2024/2/26 17:01
 */
@Slf4j
@RestController
@RequestMapping("/es")
public class TestEsCurdCtrl {

    @Resource
    private ElasticsearchClient client;

    @Resource
    public ElasticsearchHandle elasticsearchHandle;

    @PostMapping(value = "/add")
    public ResponseInfo<String> deleteDocument(@RequestParam(value = "id") String id) {
        DocumentPartESDto doc = DocumentPartESDto.builder()
                .id(id)
                .docId(id)
                .content("这是文本内容" + id)
                .type("doc")
                .build();
        elasticsearchHandle.insertDocument("doc", doc, id);
        return ResponseInfo.success();
    }

    @PostMapping(value = "/search")
    public ResponseInfo<DocumentPartESDto> searchDocument(@RequestParam(value = "id") String id) {
        GetResponse<DocumentPartESDto> doc = elasticsearchHandle.searchDocument("doc", id);
        DocumentPartESDto docDto = doc.source();
        return ResponseInfo.success(docDto);
    }

    @PostMapping(value = "/index")
    public ResponseInfo<String> createIndex(@RequestParam(value = "indexName") String indexName) {
        elasticsearchHandle.createIndex(indexName);
        return ResponseInfo.success();
    }

    public static String esMappingV2 = "{\"properties\":{\"docId\":{\"type\":\"keyword\"},\"docName\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\",\"search_analyzer\":\"ik_smart\",\"copy_to\":\"all\"},\"categoryId\":{\"type\":\"keyword\"},\"libVersionList\":{\"type\":\"keyword\"},\"content\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\",\"search_analyzer\":\"ik_smart\",\"copy_to\":\"all\"},\"title\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\",\"search_analyzer\":\"ik_smart\",\"copy_to\":\"all\"},\"all\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\",\"search_analyzer\":\"ik_smart\"}}}";

    /**
     * 创建mapping索引
     *
     * @param indexName 索引名
     */
    @PostMapping("/index/mapping")
    public void createIndexAndMapping(String indexName) {
        try {
            JsonpMapper mapper = client._transport().jsonpMapper();
            JsonParser parser = mapper.jsonProvider().createParser(new StringReader(esMappingV2));
            client.indices().create(c -> c.
                    index(indexName)
                    .mappings(TypeMapping._DESERIALIZER.deserialize(parser, mapper))
            );
        } catch (Exception e) {
            if (e.getMessage().contains("resource_already_exists_exception")) {
                log.warn("索引存在不创建");
                return;
            }
            log.error("es新增mapping索引异常:{}", e.getMessage());
            throw new EsException(ResponseCodeEnums.HTTP_STATUS_500.getCode(), "es新增mapping索引异常" + e.getMessage());
        }
    }
}
